<?php

class Model_User
{
    /**
     * 用户表对象
     * @var Zend_Db_Table_Abstract
     */
    protected $_userTable;
    /**
     * 当前用户数据
     * @var Array
     */
    protected $_user;

	/**
     * 构造方法
     *
     * 初始化一个用户，如果传递一个uid则尝试获取该用户，如果是一个数组，则用些数据填充用户对象
     *
     * @param mixed $options 用户ID或用户数据
     * @return void
     */
    public function __construct($options = null)
    {
        if (is_array($options)) {
            $this->_user = $options;
        }elseif(is_int($options)){
            $user = $this->getUserById($options);
            if($user){
                $this->_user = $user->toArray();
            }
        }
    }

    /**
     * __set() 设置一个用户的属性值
     *
     * @param string $name
     * @param mixed  $value
     */
    public function __set($name, $value)
    {
        $this->_user[$name] = $value;
    }

    /**
     * __get() 返回一个用户的属性值
     *
     * @param  string $name
     * @return mixed
     */
    public function __get($name)
    {
        if(isset($this->_user[$name])){
            return $this->_user[$name];
        }
        trigger_error('属性 ' . $name . '" 不存在', E_USER_NOTICE);
        return NULL;
    }

    /**
     * 魔术方法，用来设置或返回用户的属性
     * 如getRealname(),setRealname('卢于静')
     */
    public function __call($method, $args)
    {
        $property = strtolower(substr($method,3));
        if(substr($method,0,3) == 'set'){
            if(isset($this->_user[$property])&&is_scalar($args)){
                $this->_user[$property] = $args;
                return ;
            }elseif (is_array($args)){
                return $this->setUser($args);
            }
        }elseif(substr($method,0,3) == 'get'){
            if(isset($this->_user[$property])){
                return $this->_user[$property];
            }
            return ;
        }
        throw new Exception('方法调用错误，不存在'.$method.'这个方法！');
    }

	/**
     * 设置用户表
     *
     * @param mixed $dbTable
     * @return Model_User
     */
    public function setTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_userTable = $dbTable;
        return $this;
    }

    /**
     * 获取用户表
     *
     * @return Zend_Db_Table
     */
    public function getTable()
    {
        if(null === $this->_userTable){
            $this->setTable('Model_DbTable_User');
        }
        return $this->_userTable;
    }

    /**
     * 根据UID获取一个用户
     *
     * @param int $uid
     * @return Model_User
     */
    public function getUserById($uid)
    {
        $result = $this->getTable()->find($uid);
        if (0 == count($result)) {
            return;
        }
        $user = $result->current();
        $this->_user = $user->toArray();
        return $this;
    }

    /**
     * 删除用户
     *
     * @param mixed $uid Array|int
     * @return bool
     */
    public function deleteUser($uid)
    {
        if(is_array($uid)){
            return $this->getTable()->delete(array('uid IN (?)'=>$uid));
        }else{
            return $this->getTable()->delete(array('uid=?'=>$uid));
        }
    }

    /**
     * 用数据构建一个用户
     *
     * @return Model_User
     */
    public function setUser(Array $user)
    {
        if(!empty($this->_user)){
            if(isset($this->_user['uid'])){
            	/**
                 * 不用array_merge防止用户传递非法数组
                 */
                foreach ((array)$this->_user as $key=>$value){
                    if(isset($user[$key])){
                        $this->_user[$key] = $user[$key];
                    }
                }
            }else{
                $this->_user = array_merge($this->_user,$user);
            }
        }else{
            $this->_user = $user;
        }
        return $this;
    }

    /**
     * 获取所有用户
     *
	 * @param  array $where  形式为(fieldName,  and/Or, compare, value)
     * @param  array $order  形式为(fieldName, order)
     * @return  mixed $select
     */
    public function fetchAll(Array $where = array(), Array $order = array(array('id','DESC')))
    {
        $select = $this->getTable()->select();
        foreach ($where AS $w){
	        if ($w[1] == 'or') {
	        	$select->orWhere($w[0] . $w[2] . "?", $w[3]);
	        } else {
	            $select->where($w[0] . $w[2] . "?", $w[3]);
	        }
	    }
	    foreach ($order as $o) {
	    	$select->order($o[0] . " " . $o[1]);
	    }
	    return $select;
    }

    /**
     * 保存用户
     *
     * @param Array $user
     * @return
     */
    public function save(array $user = array())
    {
        $uid = $this->getUid();
        if(!empty($user)){
            $this->setUser($user);
        }
        $fields = $this->getTable()->info(Zend_Db_Table_Abstract::COLS);
        foreach ($this->_user as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($this->_user[$field]);
            }
        }
        $data = $this->_user;
        $result = Hm_Util::validateUser($data);
        if(true !== $result){
            throw new Exception($result);
        }
        if(null === $uid){
            $data['password'] = md5($data['password']);
            $data['reg_time'] = time();
            $data['reg_ip'] = Hm_Util::getip();
            return $this->getTable()->insert($data);
        }else{
            unset($data['uid']);
            return $this->getTable()->update($data,array('uid = ?'=>$uid));
        }
    }

    /**
     * 将用户数据转换为数组
     *
     * @return Array
     */
    public function toArray()
    {
        return (array)$this->_user;
    }

}